/**
 * @Title: UserServiceImpl
 * @Package cn.com.yiqi.wsc.service.user.impl
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @author 会员系统组-胥钰淋
 * @date 2017/2/9 18:08
 * @version V1.0
 */
package cn.com.yiqi.wsc.service.user.impl;

import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultStatusEnum;
import cn.com.yiqi.wsc.dao.func.FunctionDao;
import cn.com.yiqi.wsc.dao.role.RoleDao;
import cn.com.yiqi.wsc.dao.role.RoleUserDao;
import cn.com.yiqi.wsc.dao.user.UserDao;
import cn.com.yiqi.wsc.dao.user.criteria.UserCriteria;
import cn.com.yiqi.wsc.entity.role.Role;
import cn.com.yiqi.wsc.entity.role.RoleUser;
import cn.com.yiqi.wsc.entity.user.User;
import cn.com.yiqi.wsc.entity.user.UserEntity;
import cn.com.yiqi.wsc.enumeration.CommonEnum;
import cn.com.yiqi.wsc.enumeration.UserType;
import cn.com.yiqi.wsc.service.user.UserService;
import cn.com.yiqi.wsc.service.user.dataobject.QueryUserDO;
import cn.com.yiqi.wsc.service.user.dataobject.UserDO;
import cn.com.yiqi.wsc.service.user.dataobject.UserForModifyPassword;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author 会员系统组-胥钰淋
 * @ClassName: UserServiceImpl
 * @Description: TODO
 * @date 2017/2/9 18:08
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleUserDao roleUserDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private FunctionDao functionDao;

    @Resource(name = "encoder")
    private BCryptPasswordEncoder encoder;


    @Transactional
    @Override
    public Result insertUser(UserDO userDO) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        //密码加密
        userDO.setPassword(encoder.encode(userDO.getPassword()));
        userDao.insert(userDO);


        List<RoleUser> roleUsers = null;
        Integer userId = userDO.getId();

        List<Integer> roleIds = userDO.getRoleIds();

        if (roleIds != null && !roleIds.isEmpty()) {
            roleUsers = new ArrayList<>();
            warpRoleUser(roleUsers, userId, roleIds);
        }


        //添加user_role记录
        if (UserType.seller.getValue() == userDO.getType()) {
            //如果是商家
            roleUsers = new ArrayList<>();

            RoleUser roleuser = new RoleUser();
            //固定值1商家账户
            roleuser.setRoleId(1);
            roleuser.setUserId(userId);
            roleUsers.add(roleuser);

        }

        if (roleUsers != null) {
            roleUserDao.insertBatch(roleUsers);
        }

        return result;
    }

    @Transactional
    @Override
    public Result updateUser(UserDO userDO) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        userDO.setUpdateUserId(getCurrentUserId());
        userDO.setPassword(null);
        userDao.update(userDO);

        List<RoleUser> roleUsers = null;
        Integer userId = userDO.getId();

        List<Integer> roleIds = userDO.getRoleIds();

        if (roleIds != null && !roleIds.isEmpty()) {
            //删除user_role
            roleUserDao.deleteByUserId(userDO.getId());
            roleUsers = new ArrayList<>();
            warpRoleUser(roleUsers, userId, roleIds);
        }

        //重新添加
        if (roleUsers != null) {
            roleUserDao.insertBatch(roleUsers);
        }


        return result;
    }

    @Override
    public Result detail(UserDO userDO) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        User user = userDao.get(userDO);

        List<Role> roles = roleDao.getRoleByUserId(userDO.getId());


        List<Integer> roleIds = new ArrayList<>();
        if (roles != null && !roles.isEmpty()) {

            for (Role role : roles) {
                roleIds.add(role.getId());
            }

        }
        BeanUtils.copyProperties(user, userDO);
        userDO.setRoleIds(roleIds);

        result.putData("detail", userDO);


        result.putData("roleList", roles);

        return result;
    }

    @Override
    public Result delete(User user) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        User userForDelete = new User();
        userForDelete.setDelete(CommonEnum.DELETED.getValue());
        userForDelete.setId(user.getId());

        userDao.update(userForDelete);

        return result;
    }

    @Override
    public Result enable(User user) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        User userForEnable = new User();
        userForEnable.setEnabled(CommonEnum.ENABLE.getValue());
        userForEnable.setId(user.getId());

        userDao.update(userForEnable);

        return result;
    }

    @Override
    public Result disable(User user) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        User userForDisable = new User();
        userForDisable.setEnabled(CommonEnum.DISABLE.getValue());
        userForDisable.setId(user.getId());

        userDao.update(userForDisable);

        return result;
    }

    private void warpRoleUser(List<RoleUser> roleUsers, Integer userId, List<Integer> roleIds) {
        for (Integer roleId : roleIds) {
            RoleUser roleuser = new RoleUser();
            roleuser.setRoleId(roleId);
            roleuser.setUserId(userId);

            roleUsers.add(roleuser);
        }
    }

    @Override
    public List<UserEntity> queryUserList(QueryUserDO queryUserDO) {


        return null;
    }

    @Override
    public Set<String> findRoles(String username) {

        return null;
    }

    @Override
    public Set<String> findPermissions(String username) {

        User user = findByUsername(username);

        if (user == null) {
            return null;
        }

        List<Integer> roleIds = roleDao.getRoleIdsByUserId(user.getId());

        if (!CollectionUtils.isEmpty(roleIds)) {
            return functionDao.getFunctionCode(roleIds);
        }

        return null;
    }

    @Override
    public User findByUsername(String username) {
        return userDao.getUserByUsername(username);
    }

    @Override
    public UserEntity findUsernameAndPasswordByUsername(String username) {
        UserEntity user = null;
        try {
            user = userDao.getUserPasswordByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return user;
    }

    @Override
    public Result pageList(UserCriteria criteria) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        PageHelper.startPage(criteria.getCurrentPage(), criteria.getPageSize());
        PageHelper.orderBy("d_reg_time DESC");
        PageInfo<User> pageInfo = new PageInfo<>(userDao.pageList(criteria));

        result.putData("list", pageInfo.getList());
        result.putData("total", pageInfo.getTotal());

        return result;
    }

    @Override
    public Integer getCurrentUserId() {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        return findByUsername(username).getId();
    }

    @Override
    public User getCurrentUser() {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        return findByUsername(username);
    }

    @Override
    @Transactional
    public Integer modifyPassword(UserForModifyPassword user) {
//        String password = encoder.encode(user.getPassword());
        if (encoder.matches(user.getPassword(), getCurrentUser().getPassword())) {
            User userSa = new User();
            userSa.setId(getCurrentUserId());
            userSa.setPassword(encoder.encode(user.getNewPassword()));
            userDao.update(userSa);
            return 1;
        } else {
            return 0;
        }

    }

    @Override
    public Result getUserDetail(UserDO userDO) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        User user = userDao.get(userDO);
        user.setPassword(null);
        user.setOrgId(null);
        result.putData("myInfo", user);
        return result;
    }

    @Override
    public boolean isExist(String username) {
        return findByUsername(username) != null;
    }

    @Override
    @Transactional
    public Result resttingPassword(UserForModifyPassword user) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        if (user.getId() != null) {
            User userSa = new User();
            userSa.setId(user.getId());
            userSa.setInsertUserId(getCurrentUserId());
            userSa.setPassword(encoder.encode("123456"));
            result.putData("rtp", userDao.update(userSa));
            return result;
        }
        result.setErrMsg("用户id为空");
        return result;


    }

}
